// pages/userProfile/index.js
const app = getApp()

Page({
  data: {
    userInfo: null,
    isNewUser: false,
    username: '',
    avatarUrl: '',
    gender: 0, // 0=未知,1=男,2=女
    faction: '',
    genderOptions: [
      { value: 0, label: '未知' },
      { value: 1, label: '男' },
      { value: 2, label: '女' }
    ],
    factionOptions: [
      { value: '黑桃', label: '♠ 黑桃' },
      { value: '红桃', label: '♥ 红桃' },
      { value: '梅花', label: '♣ 梅花' },
      { value: '方片', label: '♦ 方片' }
    ],
    previewCharacter: null,
    loading: false
  },

  onLoad() {
    this.getUserInfo()
  },

  // 获取用户信息
  async getUserInfo() {
    this.setData({ loading: true })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'getUserInfo'
        }
      })

      if (result.result.success) {
        if (result.result.isNewUser) {
          // 新用户，显示个人信息填写页面
          this.setData({
            isNewUser: true,
            loading: false
          })
        } else {
          // 老用户，显示现有信息并允许编辑
          const user = result.result.data.user
          this.setData({
            userInfo: user,
            characterInfo: result.result.data.character,
            username: user.username || '',
            avatarUrl: user.avatarUrl || '',
            gender: user.gender || 0,
            faction: user.faction || '',
            isNewUser: false,
            loading: false
          })
          // 更新角色预览
          this.updateCharacterPreview()
        }
      } else {
        wx.showToast({
          title: result.result.errMsg || '获取用户信息失败',
          icon: 'none'
        })
        this.setData({ loading: false })
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const tempFilePath = res.tempFilePaths[0]
        
        try {
          // 上传图片到云存储
          const uploadResult = await wx.cloud.uploadFile({
            cloudPath: `avatars/${Date.now()}.jpg`,
            filePath: tempFilePath
          })
          
          this.setData({
            avatarUrl: uploadResult.fileID
          })
        } catch (error) {
          console.error('上传头像失败:', error)
          wx.showToast({
            title: '上传头像失败',
            icon: 'none'
          })
        }
      }
    })
  },

  // 输入昵称
  onUsernameInput(e) {
    this.setData({
      username: e.detail.value
    })
  },

  // 选择性别
  onGenderChange(e) {
    const value = parseInt(e.currentTarget.dataset.value)
    this.setData({
      gender: value
    })
    this.updateCharacterPreview()
  },

  // 选择阵营
  onFactionChange(e) {
    const value = e.currentTarget.dataset.value
    this.setData({
      faction: value
    })
    this.updateCharacterPreview()
  },

  // 更新角色预览
  updateCharacterPreview() {
    const { gender, faction } = this.data
    if (gender > 0 && faction) {
      const characterConfigs = {
        // 男性角色配置 - 国王
        "1_黑桃": {
          name: "黑桃国王",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/spade_king.png",
          description: "♠ 黑桃国王，扑克牌中的最高统治者，拥有至高无上的权力"
        },
        "1_红桃": {
          name: "红桃国王",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/heart_king.png",
          description: "♥ 红桃国王，爱心与正义的化身，守护着红桃王国的和平"
        },
        "1_梅花": {
          name: "梅花国王",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/club_king.png",
          description: "♣ 梅花国王，智慧与策略的象征，统领着梅花王国的军队"
        },
        "1_方片": {
          name: "方片国王",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/diamond_king.png",
          description: "♦ 方片国王，财富与繁荣的守护者，掌管着方片王国的宝藏"
        },
        // 女性角色配置 - 皇后
        "2_黑桃": {
          name: "黑桃皇后",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/spade_queen.png",
          description: "♠ 黑桃皇后，神秘而强大的女性统治者，掌握着黑魔法的秘密"
        },
        "2_红桃": {
          name: "红桃皇后",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/heart_queen.png",
          description: "♥ 红桃皇后，美丽与善良的化身，用爱心治愈着王国的子民"
        },
        "2_梅花": {
          name: "梅花皇后",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/club_queen.png",
          description: "♣ 梅花皇后，优雅而机智的女性领袖，用智慧守护着王国"
        },
        "2_方片": {
          name: "方片皇后",
          imageUrl: "cloud://cloud1-7g99gvjq5b86fa16.636c-cloud1-7g99gvjq5b86fa16-1318574281/characters/diamond_queen.png",
          description: "♦ 方片皇后，高贵而富有的女性统治者，掌管着王国的财富"
        }
      }
      
      const key = `${gender}_${faction}`
      const character = characterConfigs[key] || {
        name: "神秘角色",
        imageUrl: "https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0",
        description: "未知的神秘角色"
      }
      
      this.setData({
        previewCharacter: character
      })
    }
  },

  // 创建用户
  async createUser() {
    if (!this.data.username.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }

    if (!this.data.avatarUrl) {
      wx.showToast({
        title: '请选择头像',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    try {
      const result = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'createUser',
          username: this.data.username.trim(),
          avatarUrl: this.data.avatarUrl,
          gender: this.data.gender,
          faction: this.data.faction
        }
      })

      if (result.result.success) {
        wx.showToast({
          title: '创建成功',
          icon: 'success'
        })
        
        // 保存用户信息和角色信息到本地
        this.setData({
          userInfo: result.result.data.user,
          characterInfo: result.result.data.character,
          isNewUser: false
        })
        
        // 显示角色信息
        if (result.result.data.character) {
          setTimeout(() => {
            wx.showModal({
              title: '角色创建成功',
              content: `恭喜您获得角色：${result.result.data.character.name}\n\n${result.result.data.character.description}`,
              showCancel: false,
              confirmText: '开始游戏',
              success: () => {
                wx.switchTab({
                  url: '/pages/index/index'
                })
              }
            })
          }, 1000)
        } else {
          // 跳转到主页
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/index/index'
            })
          }, 1500)
        }
      } else {
        wx.showToast({
          title: result.result.errMsg || '创建用户失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('创建用户失败:', error)
      wx.showToast({
        title: '创建用户失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 更新用户信息
  async updateUser() {
    if (!this.data.username.trim()) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }

    this.setData({ loading: true })

    try {
      const result = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'updateUser',
          username: this.data.username.trim(),
          avatarUrl: this.data.avatarUrl,
          gender: this.data.gender,
          faction: this.data.faction
        }
      })

      if (result.result.success) {
        wx.showToast({
          title: '更新成功',
          icon: 'success'
        })
        
        // 更新本地用户信息
        this.setData({
          userInfo: result.result.data.user,
          characterInfo: result.result.data.character
        })
        
        // 更新角色预览
        this.updateCharacterPreview()
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        wx.showToast({
          title: result.result.errMsg || '更新用户失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('更新用户失败:', error)
      wx.showToast({
        title: '更新用户失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  }
})

